How to mock private methods in PowerMockito?

by jeanie_reilly , in category: Java , a year ago

How to mock private methods in PowerMockito?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

Member

by emma , a year ago

@jeanie_reilly 

To mock a private method using PowerMockito, you can use the org.powermock.api.mockito.PowerMockito.when() method in combination with the org.powermock.reflect.Whitebox.invokeMethod() method. Here's an example of how you can do this:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.powermock.reflect.Whitebox;

import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.when;

@RunWith(PowerMockRunner.class)
@PrepareForTest(MyClass.class)
public class MyClassTest {

    @Mock
    private Dependency dependency;

    @Test
    public void testPrivateMethod() throws Exception {
        MyClass myClass = new MyClass(dependency);

        when(dependency.doSomething()).thenReturn(true);
        PowerMockito.when(Whitebox.invokeMethod(myClass, "privateMethod")).thenReturn("mocked result");

        String result = myClass.callPrivateMethod();
        assertEquals("mocked result", result);
    }
}


This test will create a mock object for the Dependency class and use PowerMockito to mock the private method privateMethod() in the MyClass class. The test will then invoke the callPrivateMethod() method on the MyClass object and verify that it returns the expected result.


It's important to note that the @RunWith(PowerMockRunner.class) and @PrepareForTest(MyClass.class) annotations are required in order for this test to work. The @RunWith(PowerMockRunner.class) annotation is used to specify that the PowerMockRunner should be used to run the test, and the @PrepareForTest(MyClass.class) annotation is used to specify that the MyClass class will be prepared for testing (i.e., its private methods will be made accessible).

by edison.lang , 4 months ago

@jeanie_reilly 

Please note that PowerMockito is primarily intended for unit testing legacy code with poor design or code that is hard to modify. In general, mocking private methods is not recommended, as it can lead to brittle tests and make it difficult to refactor code. It is more advisable to focus on testing the public behavior of your classes instead.